/**
 * @name 简单状态管理模式-全局状态
 * @author wangsongle
 * @description 2021/12/08
 * @copyright http://songle.wang
 * @version 2.0
 */

import ViewUI from 'view-design'
import router from '../router'
import page from './page'
import { Rest } from '../libs/Request'
import util from '../libs/util'
export default {
    debug: true,
    system: new Object,
    state: {
        //会话密钥{对请求消息进行加密的密钥}
        session: null,
        //访问令牌
        token: null,
        //用户信息
        user: Object,
        //公司信息
        org: Object,
        //门店信息
        shop: Object,
        //仓库
        wms: Object,
        //树
        tree: Array,
        //对象存储STS访问凭证
        oss: {
            type: Object,
            default: {
                keyId: null, // 从STS服务获取的临时访问密钥ID
                keySecret: null, //从STS服务获取的临时访问密钥Secret
                token: null, // 从STS服务获取的安全令牌
                expire: null //STS凭证过期时间
            }
        },
        sessionReadyCallback: [],
        initStoreCallbank: [],
        initOrgCallbank: [],
        initWmsCallbank: []
    },
    setSession(value) {
        this.state.session = value
        if(this.debug) console.debug('setSession -> ',value)
    },
    getSession() {
        return this.state.session
    },
    setToken(value) {
        this.state.token = value
        if(this.debug) console.debug('setToken -> ',value)
    },
    getToken() {
        return this.state.token
    },
    setUser(key,value) {
        this.state.user[key] = value
        util.setCache(key,value)
        if(this.debug) console.debug('setUser -> ',key,value)
    },
    getUser(key) {
        return this.state.user[key] || util.getCache(key)
    },
    checkAuthCode(key) {
        if(this.state.user['authCode']) {
            let codes = this.state.user['authCode'].split(',')
            if(codes.indexOf(key) > -1) {
                return true
            }
        }
        return false
    },
    setOrg(key,value) {
        this.state.org[key] = value
        util.setCache(key,value)
        if(this.debug) console.debug('setOrg -> ',key,value)
    },
    getOrg(key) {
        return this.state.org[key] || util.getCache(key)
    },
    setShop(key,value) {
        this.state.shop[key] = value
        util.setCache(key,value)
        if(this.debug) console.debug('setShop -> ',key,value)
    },
    getShop(key) {
        return this.state.shop[key] || util.getCache(key)
    },
    setWms(key,value) {
        this.state.wms[key] = value
        util.setCache(key,value)
        if(this.debug) console.debug('setWms -> ',key,value)
    },
    getWms(key) {
        return this.state.wms[key] || util.getCache(key)
    },
    setSystem(key,value) {
        this.system[key] = value
        util.setCache(key,value)
        if(this.debug) console.debug('setSystem -> ',key,value)
    },
    getSystem(key) {
        return this.system[key] || util.getCache(key)
    },
    setOss(key,value) {
        this.state.oss[key] = value
        if(this.debug) console.debug('setOss -> ',key,value)
    },
    getOss(key) {
        return this.state.oss[key]
    },
    setTree(value) {
        this.state.tree = value
        if(this.debug) console.debug('setTree -> ',value)
    },
    getTree() {
        return this.state.tree
    },
    setSessionReadyCallback(value) {
        if(value instanceof Function){
            this.state.sessionReadyCallback.push(value)
        }
    },
    setInitStoreCallbank(value) {
        if(value instanceof Function){
            this.state.initStoreCallbank.push(value)
        }
    },
    setInitOrgCallbank(value) {
        if(value instanceof Function){
            this.state.initOrgCallbank.push(value)
        }
    },
    setInitWmsCallbank(value) {
        if(value instanceof Function){
            this.state.initWmsCallbank.push(value)
        }
    },
    
    /**
     * 自动登录
     * @param {回调函数} callback 
     */
    autoLogin(callback){
        if(localStorage.getItem('refresh_token') && localStorage.getItem('refresh_token') != 'undefined'){
            this.refresh().then((data)=>{
                //菜单树
                this.myTree()
                //组织信息
                this.myOrg()
                //店铺信息
                if(data.shopId) {
                    this.myShop(data.shopId)
                }
                //仓库信息
                if(data.warehouseId) {
                    this.myWarehouse(data.warehouseId)
                }
                //回调
                callback(data)
            }).catch((err)=>{
                console.debug(err)
                this.login()
            })
        } else {
            this.login()
        }
    },
    login() {
        ViewUI.Message.error({
            content: '超时请重新登录',
            duration: 2,
            onClose: ()=> {
                router.push({
                    name: 'login'
                })
            }
        })
    },
    //刷新access_token
    refresh(){
        return new Promise((resolve,reject)=>{
            const refresh_token = localStorage.getItem('refresh_token')
            new Rest({
                gateway: 'agrobiz',
                service: "agrobiz-uc",
                url: "/v1.0/open-src/admin/refresh",
                action: (res) => {
                    if (res.data.code === 20000) {
                        let data = res.data.data
                        //初始化用户缓存
                        this.initUser(data)
                        //执行回调任务---刷新页面时可能会用到
                        if(this.state.sessionReadyCallback.length > 0) {
                            this.state.sessionReadyCallback.forEach(element => {
                                element()
                            })
                            //清空回调任务
                            this.state.sessionReadyCallback.length = 0
                        }
                        resolve(data)
                    } else {
                        reject(res.data.msg)
                    }
                }
            }).refresh(refresh_token)
        })
    },

    /**
     * 我的菜单树
     */
    myTree(){
        return new Promise((resolve,reject)=>{
            if(true) {
                resolve(true)
            } else {
                reject('没有权限')
            }
        })
    },

    /**
     * 我的组织
     */
    myOrg(){
        return new Promise((resolve,reject)=>{
            new Rest({
                gateway: 'agrobiz',
                service: "agrobiz-uc",
                url: "/v1.0/plus/org/info/by/type",
                query: {
                    equal: 0 //0购物商城，1供应链
                },
                action: (res) => {
                    if (res.data.code === 20000 && res.data.data) {
                        let result = res.data.data
                        this.setOrg('orgId', result.orgId)
                        this.setOrg('orgName', result.orgName)
                        this.setOrg('orgMode', result.orgMode)
                        this.setOrg('mchId', result.mchId)

                        if(this.state.initOrgCallbank.length > 0) {
                            this.state.initOrgCallbank.forEach(element => {
                                element(result)
                            })
                            //清空回调任务
                            this.state.initOrgCallbank.length = 0
                        }
                        resolve(true)
                    } else {
                        reject(res.data.msg)
                    }
                }
            }).get()
        })
    },

    /**
     * 我的店铺
     */
    myShop(shopId){
        new Rest({
            gateway: 'agroerp',
            service: "agroerp-shop",
            url: "/v1.0/shop/id",
            query: {
                equal: shopId
            },
            action: (res) => {
                if (res.data.code === 20000) {
                    let result = res.data.data
                    this.setShop('shopId', result.shopId)
                    this.setShop('shopName', result.shopName)
                    this.setShop('shopType', result.shopType)

                    if(this.state.initStoreCallbank.length > 0) {
                        this.state.initStoreCallbank.forEach(element => {
                            element(result)
                        })
                        //清空回调任务
                        this.state.initStoreCallbank.length = 0
                    }
                }
            },
        }).get()
    },

    /**
     * 我的仓库
     */
    myWarehouse(warehouseId){
        new Rest({
            gateway: 'agroerp',
            service: "agroerp-wms",
            url: "/v1.0/plus/warehouse/detail",
            query: {
                equal: warehouseId
            },
            action: (res) => {
                if (res.data.code === 20000) {
                    this.setWms("countyCode", res.data.data.countyCode)
                    this.setWms("warehouseId", res.data.data.warehouseId)
                    this.setWms("warehouseName", res.data.data.warehouseName)
                    this.setWms("addressDetail", res.data.data.addressDetail)
                    this.setWms("warehouseScopes", JSON.stringify(res.data.data.warehouseScopes))
                    sessionStorage.setItem('wmsItem',JSON.stringify(res.data.data))

                    if(this.state.initWmsCallbank.length > 0) {
                        this.state.initWmsCallbank.forEach(element => {
                            element(res.data.data)
                        })
                        //清空回调任务
                        this.state.initWmsCallbank.length = 0
                    }
                }
            },
        }).get()
    },

    //初始化用户信息
    initUser(data) {
        localStorage.setItem("refresh_token", data.refresh_token)
        this.setSession(data.session_key)
        this.setToken(data.access_token)
        this.setUser("userId", data.userId)
        this.setUser('userName', data.userName)
        this.setUser("userType", data.userType)
        this.setUser("mobile", data.unionMobile)
        this.setUser('tenantId', data.tenantId)
        this.setUser('villageCode', data.villageCode)
        this.setUser('appName', data.appName)
        this.setUser('appLogo', data.appLogo)
        this.setUser('authCode', data.authCode)
        if(data.adminConfig) {
            this.setTree(JSON.parse(data.adminConfig))
        } else {
            this.state.tree = null
        }
        if(data.userImage) {
            this.setUser('userImage', data.userImage)
        }
    },

    clear(){
        localStorage.clear()
        sessionStorage.clear()

        this.state.session = null
        this.state.token = null
        for(let key in this.state.user){
            delete this.state.user[key]
        }
        for(let key in this.state.org){
            delete this.state.org[key]
        }
        for(let key in this.state.store){
            delete this.state.store[key]
        }
        for(let key in this.state.wms){
            delete this.state.wms[key]
        }
        for(let key in this.state.tree){
            delete this.state.tree[key]
        }
        this.page.clear()
        if(this.debug) console.debug('state clear')
    },

    //注入页面级缓存状态
    page: page
}